package agent;

import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavaAgent {
	static Logger logger = LoggerFactory.getLogger(JavaAgent.class);

	public static void agentmain(String args, Instrumentation inst) {
		try {
		    
			String classesPath ="dist/";
			logger.error("class redefined:" + classesPath);
			String[] classArr = args.split(";");
			
			List<ClassDefinition> classDefList = new ArrayList<ClassDefinition>();
			for (String className : classArr) {
				Class<?> c = Class.forName(className);
				String classPath = classesPath + className.replace(".", "/") + ".class";
				logger.error("class redefined:" + classPath);
				Path pathFrom = Paths.get(classPath);
				byte[] bytesFromFile = Files.readAllBytes(pathFrom);
				ClassDefinition classDefinition = new ClassDefinition(c, bytesFromFile);
				classDefList.add(classDefinition);
			}

			inst.redefineClasses(classDefList.toArray(new ClassDefinition[classDefList.size()]));
		} catch (Exception  e) {
			logger.error("",e);;
		} finally {
			
		}
	}
}
